#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent),
      local_room_id(1),
      ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Server");
    db = DbHelper::getInstance();
    server = new QTcpServer(this);
    server->listen(QHostAddress::LocalHost, 8089);

    QObject::connect(server, &QTcpServer::newConnection, this, &Widget::onNewConnection);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::regist(TcpSocket *client, Pack pack)
{
    QStringList list = pack.getData();
    pack.clear();
    QString name = list[0];
    QString pswd = list[1];
    bool res = db->regist(name, pswd);
    if(true == res){
        pack.setErr(SUCCESS);
    }else{
        pack.setErr(ERR_REGIST);
    }

    client->write(pack.data(), pack.size());
}

void Widget::login(TcpSocket *client, Pack pack)
{
    QStringList list = pack.getData();
    pack.clear();
    QString name = list[0];
    QString pswd = list[1];
    bool res = db->login(name, pswd);
    if(true == res){
        pack.setErr(SUCCESS);
        client->setName(name);  //登录成功，将成功登录的用户名和当前用户的套接字进行绑定，方便以后了根据套接字查询用户
    }else{
        pack.setErr(ERR_LOGIN);
    }

    client->write(pack.data(), pack.size());

}

void Widget::createRoom(TcpSocket *client, Pack pack)
{
    // 1、产生一个房间号，把这个房间号给client管理
    QString create_room_id = QString::number(local_room_id);
    client->setCreateRoomId(create_room_id);

    pack.clear();
    pack.setType(TYPE_CREATE_ROOM);
    pack.append(create_room_id);

    // 2、发回房间号
    client->write(pack.data(), pack.size());

    // 3、房间号自增
    local_room_id += 1;

}

//客户端加入直播间
void Widget::joinRoom(TcpSocket *client, Pack pack)
{
    //把该客户端加入的直播间保存
    QStringList list = pack.getData();
    QString join_room_id = list[0];
    client->setJoinRoomId(join_room_id);

    //找到该房间号的房主，发给客户端
    QString owner_name = findUser(join_room_id);
    pack.clear();
    pack.append(owner_name);
    pack.append(join_room_id);
    client->write(pack.data(), pack.size());
}

TcpSocket *Widget::findClient(QTcpSocket *c)
{
    for(auto it:tcpsocket_vector){
        if(it->getSock() == c){
            return it;
        }
    }

    return NULL;
}

QString Widget::findUser(const QString &room_id)
{
    for(auto it:tcpsocket_vector){
        if(room_id == it->getCreateRoomId()){
            return it->getName();
        }
    }

    //没找到返回空
    return QString();
}

void Widget::onNewConnection()
{
    QTcpSocket* c = server->nextPendingConnection();
    TcpSocket* client = new TcpSocket(c, this);
    tcpsocket_vector.push_back(client);

    QObject::connect(client->getSock(), &QTcpSocket::readyRead, this, &Widget::onReadyRead);
    qDebug() << client->peerAddress();
    qDebug() << client->peerPort();
    
}

void Widget::onDisConnected()
{

}

void Widget::onReadyRead()
{

    QTcpSocket* c = dynamic_cast<QTcpSocket* >(sender());
    TcpSocket* client = findClient(c);

    while(1){

        qDebug() << "new message..." <<endl;

        Pack pack;
        //处理粘包问题
        int size = 0;
        int res = client->read((char*)&size, 4);
        if(res == 0){break;}

        client->read(pack.data()+4, size-4);

        switch (pack.getType()) {
            case TYPE_REGIST:
                regist(client, pack);
                break;
            case TYPE_LOGIN:
                login(client, pack);
                break;
             case TYPE_CREATE_ROOM:
                createRoom(client, pack);
                break;
             case TYPE_JOIN_ROOM:
                joinRoom(client, pack);
                break;
        }
    }

}

